package com.framework.servlet;

import com.puyun.framework.sys.config.dao.ParaDataDAO;
import com.puyun.framework.sys.obj.object.dao.ObjectDAO;
import com.puyun.framework.sys.quartz.QuartzManager;
import com.puyun.framework.utils.CacheUtils;
import com.puyun.framework.utils.CommonUtils;
import com.puyun.framework.utils.DBManager;
import com.puyun.framework.utils.FileConfigParser;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class InitServlet1 implements ServletContextListener {
	private Logger log = Logger.getLogger(InitServlet1.class.getName());

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		initDBParam();
		DBManager db = new DBManager();
		try {
			db.newConnection();
			this.log.info("数据库连接成功!");
		} catch (Exception e) {
			e.printStackTrace();
			this.log.error("数据库连接失败，请检查数据库连接配置参数：" + e);
			System.exit(-1);
		} finally {
			db.closeConnection();
			this.log.info("数据库连接成功!");
		}

		boolean retFlag = false;
		retFlag = true;
		if (retFlag) {
			this.log.info("系统签名认证成功");
		} else {
			this.log.info("系统签名认证失败,请重新申请license : ");
			System.exit(-1);
		}

		this.log.info("初始化系统参数 ：begin");
		initParaData();
		initObjTypeAndState();
		initSysOption();
		initIdapMap();
		initEmail();
		this.log.info("初始化系统参数 : end");

		this.log.info("初始化定时任务 : begin");
		initQuartz();
		this.log.info("初始化定时任务 : end");

		this.log.info("初始化文档参数 : begin");
		try {
			initDocConfig();
		} catch (Exception e) {
			this.log.info("初始化文档参数  失败   : " + e);
		}
		this.log.info("初始化文档参数  : end");

		this.log.info("初始化实体参数  : begin");
		initObjectConfig();
		this.log.info("初始化实体参数  : end");

		this.log.info("初始化 文档转换参数 : begin");
		initDocConvert();
		this.log.info("初始化 文档转换参数  : end");
	}

	private boolean initParaData() {
		boolean retFlag = true;
		try {
			ParaDataDAO paraDao = new ParaDataDAO();
			Map cconfigData = paraDao.paraConfigData();
			if (cconfigData != null) {
				List confiList = (List) cconfigData.get("rows");
				if ((confiList != null) && (confiList.size() > 0))
					for (int i = 0; i < confiList.size(); i++) {
						Map temp = (HashMap) confiList.get(i);
						String paratypecode = (String) temp.get("paratypecode");
						String paratype = (String) temp.get("paratype");
						if ("1".equals(paratype))
							CacheUtils.paraMap.put("paratypecode", paraDao.paraDataList(paratypecode));
					}
			}
		} catch (Exception e) {
			this.log.error("初始化数据字典数据失败：initParaData()" + e);
		}
		return retFlag;
	}

	private boolean initDBParam() {
		boolean flag = true;
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			String filepath = Thread.currentThread().getContextClassLoader().getResource("config/db.properties")
					.getFile();
			filepath = URLDecoder.decode(filepath, "UTF-8");

			fis = new FileInputStream(filepath);

			prop.load(fis);

			DBManager.connType = prop.getProperty("connType").trim();
			DBManager.database = prop.getProperty("database").trim();
			DBManager.dataSource = prop.getProperty("dataSource").trim();

			if ("mysql".equals(DBManager.database)) {
				DBManager.name_mysql = prop.getProperty("name_mysql").trim();
				DBManager.url_mysql = prop.getProperty("url_mysql").trim();
				DBManager.username_mysql = prop.getProperty("username_mysql").trim();
				DBManager.password_mysql = prop.getProperty("password_mysql").trim();
			} else if ("oracle".equals(DBManager.database)) {
				DBManager.name_orcl = prop.getProperty("name_orcl").trim();
				DBManager.url_orcl = prop.getProperty("url_orcl").trim();
				DBManager.username_orcl = prop.getProperty("username_orcl").trim();
				DBManager.password_orcl = prop.getProperty("password_orcl").trim();
			}
		} catch (Exception e) {
			this.log.error("初始化数据库连接参数失败：initDBParam()" + e);
			flag = false;

//			if (fis != null)
//				try {
//					fis.close();
//				} catch (IOException ex) {
//					this.log.error(getClass(), ex.fillInStackTrace());
//				}
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					this.log.error(getClass(), e.fillInStackTrace());
				}
			}
		}

		return flag;
	}

	private boolean initQuartz() {
		boolean flag = true;
		DBManager db = new DBManager();
		try {
			db.newConnection();
			StringBuffer sql = new StringBuffer();
			sql.append("select t.sname,t.scode,t.classname,t.cronname,t.maxtime,t.classname");
			sql.append(" from cfg_schedule_task t");
			sql.append(" where t.istate = 1");
			this.log.info(sql.toString());
			List objList = db.executeQueryList(sql.toString());
			if ((objList != null) && (objList.size() > 0)) {
				for (int i = 0; i < objList.size(); i++) {
					Map mm = (HashMap) objList.get(i);
					String sname = (String) mm.get("sname");
					String scode = (String) mm.get("scode");
					String classname = (String) mm.get("classname");
					String cronname = (String) mm.get("cronname");
					String maxtime = (String) mm.get("maxtime");
					if ((scode != null) && (classname != null) && (cronname != null)) {
						try {
							QuartzManager.addJob(scode, classname, cronname.trim());
							this.log.info("系统定时跑批任务注册：scode=" + scode + ";classname=" + classname + ";cronname="
									+ cronname);
						} catch (Exception e) {
							this.log.error("系统定时跑批任务注册失败：scode=" + scode + ";classname=" + classname
									+ ";cronname=" + cronname);
						}
					}
				}
			}

		} catch (Exception e) {
			this.log.error("系统定时跑批任务注册失败：" + e);
			flag = false;
		} finally {
			db.closeConnection();
		}
		return flag;
	}

	public boolean initObjTypeAndState() {
		boolean retFlag = true;
		try {
			ObjectDAO objDao = new ObjectDAO();
			Map dataMap = objDao.objectList(null, null, 999, 1);
			if (dataMap != null) {
				List objectList = (List) dataMap.get("rows");
				if ((objectList != null) && (objectList.size() > 0)) {
					CommonUtils common = new CommonUtils();
					for (int i = 0; i < objectList.size(); i++) {
						Map temp = (HashMap) objectList.get(i);
						String objid = (String) temp.get("iid");
						if (StringUtils.isNotBlank(objid)) {
							CommonUtils.searchItypeList(Integer.parseInt(objid));
							CommonUtils.searchIstateList(Integer.parseInt(objid));
						}
					}
				}
			}
		} catch (Exception e) {
			this.log.error("初始化数据字典数据失败：initParaData()" + e);
		}
		return retFlag;
	}

	private void initDocConfig() throws Exception {
		CacheUtils.pathMap = FileConfigParser.getFilePathMap();
	}

	private void initObjectConfig() {
		ObjectDAO ob = new ObjectDAO();
		List list = ob.objectInfo();
		for (int i = 0; i < list.size(); i++) {
			Map map = (Map) list.get(i);
			String objid = map.get("objid").toString();
			CacheUtils.objectMap.put(objid, map);
		}
	}

	private boolean initEmail() {
		boolean flag = true;
		DBManager db = new DBManager();
		try {
			db.newConnection();
			StringBuffer sql = new StringBuffer();
			sql.append("select a.smtp,a.susername,a.spassword,a.sfrom,a.sto,a.istate from cfg_mail a");
			sql.append(" where a.delflag = 0 and a.iid = 1");
			this.log.info(sql.toString());
			List objList = db.executeQueryList(sql.toString());
			for (int i = 0; i < objList.size(); i++) {
				Map map = (Map) objList.get(i);
				String smtp = map.get("smtp").toString();
				if ((map.get("smtp") != null) && (map.get("smtp").toString().length() > 0)) {
					com.puyun.framework.utils.EmailUtils.smtp = map.get("smtp").toString();
				}
				if ((map.get("susername") != null) && (map.get("susername").toString().length() > 0)) {
					com.puyun.framework.utils.EmailUtils.username = map.get("susername").toString();
				}
				if ((map.get("spassword") != null) && (map.get("spassword").toString().length() > 0)) {
					com.puyun.framework.utils.EmailUtils.password = map.get("spassword").toString();
				}
				if ((map.get("sto") != null) && (map.get("sto").toString().length() > 0)) {
					com.puyun.framework.utils.EmailUtils.from_to = map.get("sto").toString();
				}
				if ((map.get("istate") != null) && (map.get("istate").toString().length() > 0))
					com.puyun.framework.utils.EmailUtils.istate = Integer.parseInt(map.get("istate").toString());
				else {
					com.puyun.framework.utils.EmailUtils.istate = 1;
				}

				this.log.info("初始化邮箱配置参数  : " + map);
			}
		} catch (Exception e) {
			this.log.error("初始化邮箱配置参数失败  : " + e);
			flag = false;
		} finally {
			db.closeConnection();
		}
		return flag;
	}

	private boolean initSysOption() {
		boolean flag = true;
		DBManager db = new DBManager();
		try {
			db.newConnection();
			StringBuffer sql = new StringBuffer();
			sql.append("select c.scode,c.ival from cfg_option c where c.delflag = 0");
			this.log.info(sql.toString());
			List objList = db.executeQueryList(sql.toString());
			for (int i = 0; i < objList.size(); i++) {
				Map map = (Map) objList.get(i);
				String scode = map.get("scode").toString();
				String ival = map.get("ival").toString();
				CacheUtils.sysOptionMap.put(scode, ival);
			}
			this.log.info("系统配置参数  : " + CacheUtils.sysOptionMap);
		} catch (Exception e) {
			this.log.error("初始化系统配置项失败：" + e);
			flag = false;
		} finally {
			db.closeConnection();
		}
		return flag;
	}

	private boolean initIdapMap() {
		boolean flag = true;
		DBManager db = new DBManager();
		try {
			db.newConnection();
			StringBuffer sql = new StringBuffer();
			sql.append(" select a.surl,a.sdn,a.sdomain from cfg_cdm_ldap a");
			this.log.info(sql.toString());
			Map mm = db.executeQueryRowMap(sql.toString());
			if (mm != null) {
				String surl = mm.get("surl") != null ? mm.get("surl").toString() : "";
				String sdn = mm.get("sdn") != null ? mm.get("sdn").toString() : "";
				String sdomain = mm.get("sdomain") != null ? mm.get("sdomain").toString() : "";
				CacheUtils.idapMap.put("surl", surl);
				CacheUtils.idapMap.put("sdn", sdn);
				CacheUtils.idapMap.put("sdomain", sdomain);
			}

			this.log.info("系统配置参数  : " + CacheUtils.sysOptionMap);
		} catch (Exception e) {
			this.log.error("初始化系统配置项失败：" + e);
			flag = false;
		} finally {
			db.closeConnection();
		}
		return flag;
	}

	private void initDocConvert() {
		FileInputStream fis = null;
		try {
			String filepath = Thread.currentThread().getContextClassLoader().getResource("config/pdf.properties")
					.getFile();
			filepath = URLDecoder.decode(filepath, "UTF-8");

			fis = new FileInputStream(filepath);

			Properties prop = new Properties();
			prop.load(fis);
			CacheUtils.docConvertMap.putAll(prop);
		} catch (Exception e) {
			this.log.error("初始化  initWebserviceUrl : " + e);

			if (fis != null)
				try {
					fis.close();
				} catch (IOException ex) {
					this.log.error(getClass(), ex.fillInStackTrace());
				}
		} finally {
			if (fis != null)
				try {
					fis.close();
				} catch (IOException e) {
					this.log.error(getClass(), e.fillInStackTrace());
				}
		}
	}

	private boolean initTableIID() {
		boolean retFlag = true;
		DBManager db = new DBManager();
		try {
			db.newConnection();
			if ("oracle".equals(DBManager.database)) {
				String tableSql = "select a.table_name from user_tables a  where a.table_name not like '%HIS%'  order by a.table_name";

				this.log.info(tableSql.toString());
				List tableMap = db.executeQueryList(tableSql);
				if ((tableMap != null) && (tableMap.size() > 0)) {
					for (int i = 0; i < tableMap.size(); i++) {
						Map mm = (HashMap) tableMap.get(i);
						String tableName = mm.get("table_name") != null ? mm.get("table_name").toString() : "";
						try {
							int maxIID = db.executeQueryInt("select max(iid)+1 from " + tableName);
							CacheUtils.iidMap.put(tableName.toUpperCase(), Integer.valueOf(maxIID));
						} catch (Exception localException1) {
						}
					}
				}

				System.out.println("===CacheUtils.iidMap====>>" + CacheUtils.iidMap.size());
			} else {
				"mysql".equals(DBManager.database);
			}

			this.log.info("初始化数据库表IID成功");
		} catch (Exception e) {
			this.log.error("初始化数据库表IID失败：" + e);
			retFlag = false;
		} finally {
			db.closeConnection();
		}
		return retFlag;
	}

}
